package yams.resource.impl;

import javafx.util.Callback;
import org.springframework.web.bind.annotation.*;
import yams.callback.IdCallback;
import yams.domain.EnumEntity;
import yams.domain.EnumItemEntity;
import yams.resource.IEnumResource;
import yams.resource.JsonCommonResource;
import yams.response.JsonResponse;
import yams.response.Response;
import yams.service.ICommonService;
import yams.service.impl.DefaultCommonService;

import javax.annotation.Resource;

/**
 * 枚举值接口
 * Created by Silence on 2016/11/1.
 */
@SuppressWarnings("unchecked")
@RestController
@RequestMapping("/enum")
public class DefaultEnumResource extends JsonCommonResource implements IEnumResource {

    private ICommonService enumService;

    @Resource
    private IdCallback idCallback;

    @RequestMapping(value = "/", method = RequestMethod.POST)
    @Override
    public JsonResponse<EnumEntity> page(@RequestBody EnumEntity enumEntity) {
        return _pageAll(enumService, enumEntity);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @Override
    public JsonResponse<EnumEntity> findById(@PathVariable String id) {
        return _findOne(enumService, id, 0);
    }

    @RequestMapping(value = "/code/{code}", method = RequestMethod.GET)
    @Override
    public JsonResponse<EnumEntity> findByCode(@PathVariable String code) {
        return _findOne(enumService, code, 1);
    }

    @RequestMapping(value = "/", method = RequestMethod.PUT)
    @Override
    public JsonResponse<EnumEntity> save(@RequestBody EnumEntity enu) {
        return _saveInfo(enumService, enu, (Callback<EnumEntity, Object>) param -> {
            if (param.getItems() != null)
                param.getItems().forEach(a -> {
                    idCallback.call(a);
                    a.setMaster(param);
                });
            return null;
        });
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @Override
    public JsonResponse<EnumEntity> delete(@PathVariable String id) {
        return _delete(enumService, id);
    }

    @Override
    public void initService() {
        if(enumService==null)
            enumService = new DefaultCommonService("enumRepository");
    }

    @RequestMapping(value = "/item/{code}", method = RequestMethod.GET)
    @Override
    public JsonResponse<EnumItemEntity> findItems(@PathVariable String code) {
        EnumEntity enumEntity = (EnumEntity) enumService.findByCode(code);
        if(enumEntity!=null)
            return JsonResponse.build(enumEntity.getItems());
        return JsonResponse.OK();
    }
}
